<template>
  <PageWrapper title="操作指南">
    <div class="container">
      <a-row class="mb-4">
        <a-col :span="12">
          <h1>文字描述:</h1>
        </a-col>
        <a-col :span="12">
          <!-- 图片上传组件 -->

          <a-upload v-model:file-list="fileList" multiple :show-upload-list="false" accept="image/*"
            :before-upload="beforeUpload" :customRequest="customUpload">
            <div v-if="fileList.length < 10">
              <a-button type="primary"> 选择多张图片 </a-button>
              <!-- <div style="margin-top: 8px">上传图片（最多10张）</div> -->
            </div>
          </a-upload>

        </a-col></a-row>

      <div>
        <a-row class="border-dashed border-2 border-gray-300"><a-col :span="12" class="left">
            <div id="profile">
              <div class="detail">
                <div ref="edit" class="textarea" contenteditable="true"></div>
              </div>
            </div>
          </a-col>
          <!-- 可编辑画布区域 -->
          <a-col :span="12" class="right">
            <div ref="canvasRef" class="edit-canvas" style=" height: 100% ">
              <div v-for="(img, index) in imageList" :key="img.id" class="draggable-item" :style="{
                transform: `translate(${img.x}px, ${img.y}px)`,
                width: img.width + 'px',
                height: img.height + 'px',
                // zIndex: img.zIndex
              }">
                <img :src="img.url" class="preview-image" :data-index="index" />
                <div class="control-bar">
                  <span class="delete-btn" @click="onDelete(index)">×</span>
                  <!-- <span class="rotate-btn" @click="rotateImage(index)">↻</span> -->
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
      <!-- 操作按钮 -->
      <a-button type="primary" @click="handleSave" class="submit-btn">
        提交保存
      </a-button>
    </div>
  </PageWrapper>
</template>

<script setup>
import { PageWrapper } from '/@/components/Page'
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import interact from 'interactjs';
import { ref, onMounted, nextTick } from 'vue';

import { getManual, uploadApi, delResource } from '/@/api/sys/common'
import { saveManual } from '/@/api/sys/product'
import { useRoute } from 'vue-router'

const baseUrl = import.meta.env.VITE_PHOTO_URL
const route = useRoute()
const softwareId = route.query.id || 0
const token = localStorage.getItem('TOKEN_KEY')
// 画布设置
const canvasHeight = ref(600);
const canvasRef = ref(null);

// 图片数据
const imageList = ref([]);
const fileList = ref([]);

const edit = ref()
// 初始化交互
onMounted(() => {
  initInteract();
});

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) message.error('只能上传图片文件');
  return isImage || Upload.LIST_IGNORE;
};
// 删除文件
const onDelete = async (index) => {
  const res = await delResource({
    token,
    key: imageList.value[index].key
  })
  if (res.success == 1) {
    message.success('已删除')
  } else {
    message.error(res.message)
  }
  imageList.value.splice(index, 1);
};

// 自定义上传处理
const customUpload = async ({ file, onSuccess }) => {
  const previewUrl = URL.createObjectURL(file);

  imageList.value.push({
    id: Date.now() + Math.random(),
    url: previewUrl,
    x: 0,
    y: 0,
    width: 200,
    height: 200,
    // zIndex: 1,
    file
  });

  onSuccess();
  handleSubmit()
  await nextTick();
  updateInteractables();
};

// 初始化拖拽缩放
const initInteract = () => {
  interact('.draggable-item').draggable({
    modifiers: [
      interact.modifiers.restrictRect({
        restriction: 'parent',
        endOnly: true
      })
    ],
    listeners: {
      move: event => {
        const index = event.target.querySelector('img').dataset.index;
        imageList.value[index].x += event.dx;
        imageList.value[index].y += event.dy;
      }
    }
  }).resizable({
    edges: { left: true, right: true, bottom: true, top: true },
    modifiers: [
      interact.modifiers.aspectRatio({
        ratio: 'preserve'
      })
    ],
    listeners: {
      move: event => {
        const index = event.target.querySelector('img').dataset.index;
        const img = imageList.value[index];

        img.width = event.rect.width;
        img.height = event.rect.height;
        img.x += event.deltaRect.left;
        img.y += event.deltaRect.top;
      }
    }
  });
};

// 更新可交互元素
const updateInteractables = () => {
  interact('.draggable-item').unset();
  initInteract();
};
const handleSave = async () => {

  const images =imageList.value.map(item=>({
    width:item.width,
    height:item.height,
    x:item.x,
    y:item.y,
    url:item.url,
    key:item.key,
    name:item.name,
  }))

  const res = await saveManual({
    token,
    data: {
      softwareId,
      content: edit.value.innerHTML,
      images: images
    },
  })
  if (res.success == 1) {
    message.success('保存成功')
    restoreTemplate()
  } else {
    message.error(res.message)
  }

}
// 删除图片
// const removeImage = (index) => {

// };

// 旋转图片
// const rotateImage = (index) => {
//   imageList.value[index].rotation += 90;
//   const img = imageList.value[index];
//   [img.width, img.height] = [img.height, img.width];
// };

// 提交数据
const handleSubmit = async () => {

  const formData = new FormData();
  // console.log(1,imageList.value)
  // imageList.value.forEach((img, index) => {
  const img = imageList.value[imageList.value.length - 1]
 const  index=imageList.value.length - 1
  formData.append(`images${index}x`, img.x);
  formData.append(`images${index}y`, img.y);
  formData.append(`images${index}width`, img.width);
  formData.append(`images${index}height`, img.height);
  // formData.append(`images[${index}][rotation]`, img.rotation);

  if (img.file) {
    formData.append(`files[${index}]`, img.file);
  }
  // });
  formData.append('token', token);
  formData.append('type', 'manual');
  formData.append('parentId', softwareId);


  for (const [key, value] of formData.entries()) {
    console.log(key, value);
  }
  // return
  try {
    const res = await uploadApi(formData)
    img.key=res.data[0].key
    img.name=res.data[0].name
    // await axios.post('/api/save-design', formData);
    // message.success('成功');
  } catch (error) {
    // message.error('保存失败');
  }
};

// 加载已有数据
// const loadSavedData = async () => {
//   try {
//     // const res = await axios.get('/api/get-design');
//     // imageList.value = res.data.map(img => ({
//     //   ...img,
//     //   url: `${CDN_BASE}${img.path}`
//     // }));
//   } catch (error) {
//     message.error('数据加载失败');
//   }
// };
const restoreTemplate = async () => {
  const res = await getManual({ softwareId })
  imageList.value = res.data.images.map(img => ({
    ...img, url: `${baseUrl}${img.url}`
  }))
  edit.value.innerHTML = res.data.content

  initInteract() // 重新初始化交互
}
// 初始化加载数据
onMounted(() => {
  restoreTemplate();
});
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}

.edit-canvas {
  position: relative;
  width: 100%;
  // border: 2px dashed #ddd;
  background: repeating-conic-gradient(#f0f0f0 0% 25%, white 0% 50%) 50% / 20px 20px;
}

.draggable-item {
  position: absolute;
  touch-action: none;
  transition: transform 0.1s;
  border: 2px solid #1890ff;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  pointer-events: none;
}

.control-bar {
  position: absolute;
  top: -25px;
  right: 0;
  display: flex;
  gap: 8px;
}

.delete-btn,
.rotate-btn {
  width: 22px;
  height: 22px;
  background: #ff4d4f;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-weight: bold;
}

.rotate-btn {
  background: #1890ff;
}

.submit-btn {
  margin-top: 20px;
  width: 200px;
}

#profile {
  width: 100%;
  margin: auto;
  background-color: #fff;
  // border: 1px solid #010101;
  padding: 50px;
  line-height: 27px;
  font-size: 18px;
  color: #000000;
  position: relative;

  h2 {
    color: #4588c0;
    text-align: center;
    font-size: 28px;
  }

  .detail {
    background: url(../../../assets/images/bg3.png) repeat;
    line-height: 47px;

    .textarea {
      border: 0;
      outline: none;
      resize: none;
      width: 100%;
      min-height: 768px;
      background: none;
      line-height: 48px;
      font-size: 18px;
    }
  }

  .company {
    position: absolute;
    bottom: 20px;
    left: -2px;
    width: 100%;
    text-align: center;
  }
}
</style>